<template>
  <div class="u-page mai-conversation-add">
    <!-- 📌 顶部栏：返回按钮 + 标题 + 发布按钮 -->
    <div class="conversation_head_weichat">
      <div @click="goBack()" class="conversation_head_back_button_weichat">
        <img src="/static/icon/common/return-icon.png" />
      </div>
      <div class="conversation_head_title_weichat">朋友圈</div>
      <div @click="sendMoments()" class="conversation_head_camera_button_weichat">
        <img src="/static/icon/moments/camera.png" />
      </div>
    </div>

    <!-- ⏳ 加载动画（初次加载朋友圈数据时显示） -->
    <div v-if="loading" class="loading-container">
      <img src="/static/icon/common/loading.gif" alt="加载中..." />
      <p>正在加载朋友圈...</p>
    </div>

    <!-- 📜 滚动区域：朋友圈主内容，加载完成后显示 -->
    <scroll-view
      class="scroll-container"
      scroll-y
      v-else
      @scrolltolower="onScrollToLower"
    >
      <!-- 🎨 顶部背景图 + 用户名 + 头像 -->
      <div class="bg_name_avatar">
        <!-- 🎨 背景图区域，可点击更换背景图 -->
        <div class="moments_bg" @click="chooseBackgroundImage">
          <img :src="userAppInfo.comments_bg || '/static/icon/moments/moments_default_bg.png'" />
        </div>

        <div class="moments_name">{{ userProfile.nick || "---设置昵称--" }}</div>
        <div class="moments_avatar">
          <img :src="userAppInfo.avatar || '/static/logo.png'" />
        </div>
      </div>

      <!-- 🔔 消息提示区域（目前未启用） -->
      <view style="text-align: center; margin-top: 50rpx;">
        <MessageTip v-if="false" text="1条新消息" icon="/static/logo.png" />
      </view>

      <!-- 📝 朋友圈列表：通过 v-for 渲染每条动态 -->
      <view v-for="moment in moments" :key="moment.id">
        <MomentCard :moment="moment" @comment-success="refreshMoment" />
      </view>

      <!-- 📦 底部提示：加载中 / 没有更多 -->
      <view style="text-align: center; color: #999; padding: 20rpx 0;">
        <text v-if="isLoadingMore">正在加载更多...</text>
        <text v-else-if="!hasMore">没有更多内容了</text>
      </view>
    </scroll-view>
  </div>
</template>

<script lang="ts" setup>
import { TUIStore, StoreName, TUIUserService } from '@tencentcloud/chat-uikit-engine';
import { TUIGlobal } from '@tencentcloud/universal-api';
import { onLoad, onUnload, onHide, onShow } from '@dcloudio/uni-app';
import { ref, onMounted, onUnmounted } from '/TUIKit/adapter-vue';
import { IUserProfile } from '/TUIKit/interface';

import MessageTip from '@/components/moments/MessageTip.vue';
import MomentCard from '@/components/moments/MomentCard.vue';
import { getMomentsList } from '@/api/moments';
import { uploadImage } from '@/api/upload'; // 你封装的上传 API
import { updateUserInfo } from '@/api/user'; // 更新用户信息 API

/* 🔄 数据状态 */
const loading = ref(true);             // 是否正在初次加载
const moments = ref([]);               // 朋友圈列表
const page = ref(1);                   // 当前分页页码
const limit = 10;                      // 每页条数
const hasMore = ref(true);             // 是否还有更多
const isLoadingMore = ref(false);      // 是否正在分页加载中
const userAppInfo = ref();				// 用户APP 里面的信息
// 用户信息 腾讯的
const userProfile = ref<IUserProfile>({});
/* 🚀 加载朋友圈列表（支持分页） */
const loadMoments = async () => {
  if (isLoadingMore.value) return;
  isLoadingMore.value = true;

  try {
	  let user_id = uni.getStorageSync("userAppInfo").id
    const data = await getMomentsList(user_id,page.value, limit);
    if (data.length < limit) hasMore.value = false;

    // 首页替换，其余分页追加
    if (page.value === 1) {
      moments.value = data;
    } else {
      moments.value = [...moments.value, ...data];
    }
  } catch (e) {
    console.error('获取朋友圈失败', e);
  } finally {
    loading.value = false;
    isLoadingMore.value = false;
  }
};
// 监控用户资料编辑
TUIStore.watch(StoreName.USER, {
  // 显示用户基本信息
  userProfile: (userProfileData: IUserProfile) => {
	userProfile.value = { ...userProfile.value, ...userProfileData }; // ✅ 强制触发更新
  },
});
/* 🪝 页面初始化时加载数据 */
onMounted(() => {
  loadMoments();
  // 读取用户信息
  userAppInfo.value = uni.getStorageSync('userAppInfo')
  // 查询自己的资料
  TUIUserService.getUserProfile().then((res: any) => {
    userProfile.value = res.data;
  });
  // 发布朋友圈成功后 刷新一下
  uni.$on('refreshMomentList', reloadMomentList)
});

onUnmounted(() => {
  uni.$off('refreshMomentList', reloadMomentList)
})

// 页面返回可触发 onShow，保险起见也加一层保障
onShow(() => {
  reloadMomentList()
})

function reloadMomentList() {
  console.log('刷新朋友圈列表')
  // 👇调用你原来加载朋友圈数据的函数，例如：
  loadMoments();
}
/* 📥 上拉触底加载更多 */
const onScrollToLower = () => {
  if (!hasMore.value || isLoadingMore.value) return;
  page.value += 1;
  loadMoments();
};
// 🖼️ 选择并上传背景图
const chooseBackgroundImage = () => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      const filePath = res.tempFilePaths[0];
      const userInfo = uni.getStorageSync('userAppInfo');

      try {
        const uploadRes = await uploadImage(filePath);
        const newBgUrl = uni.$baseUrl+uploadRes.url;

        // 更新用户信息
        await updateUserInfo(userInfo.id, {
          comments_bg: newBgUrl,
        });

        // 更新本地缓存与页面展示
        userAppInfo.value.comments_bg = newBgUrl;
        uni.setStorageSync('userAppInfo', userAppInfo.value);
        uni.showToast({ title: '背景图已更新', icon: 'success' });
      } catch (err) {
        uni.showToast({ title: '更新失败', icon: 'none' });
      }
    },
  });
};
/* 💬 评论成功后刷新本地评论 */
const refreshMoment = ({ momentId, comment }) => {
  const target = moments.value.find(m => m.id === momentId);
  if (target) {
    target.comments.push(comment);
  }
};

/* ➕ 发布朋友圈跳转 */
const sendMoments = () => {
  uni.navigateTo({ url: '/pages/moments/send' });
};

/* ⬅️ 返回上一页 */
const goBack = () => {
  uni.navigateBack();
};
</script>

<style>
/* 页面整体结构 */
.mai-conversation-add {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  overflow: hidden;
}

/* 顶部导航栏样式 */
.conversation_head_weichat {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: calc(44px + env(safe-area-inset-top));
  background-color: #f5f5f5;
  padding: 0 10rpx;
}

.conversation_head_title_weichat {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  line-height: calc(44px + env(safe-area-inset-top));
  color: #333;
}

.conversation_head_back_button_weichat,
.conversation_head_camera_button_weichat {
  width: 60px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.conversation_head_back_button_weichat img,
.conversation_head_camera_button_weichat img {
  width: 30px;
  height: 30px;
}

/* 滚动容器 */
.scroll-container {
  height: 100vh;
  overflow-y: auto;
  padding-bottom: 100rpx;
}

/* 顶部背景图 + 用户信息 */
.bg_name_avatar {
  position: relative;
  width: 100%;
  height: 240rpx;
  background-color: #fff;
  z-index: 666;
}

.moments_bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 220rpx;
}

.moments_bg img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.moments_name {
  position: absolute;
  bottom: 40rpx;
  left: 20rpx;
  font-size: 36rpx;
  font-weight: bold;
  color: white;
}

.moments_avatar {
  position: absolute;
  top: 180rpx;
  right: 20rpx;
  width: 80rpx;
  height: 80rpx;
  border-radius: 4rpx;
  overflow: hidden;
  border: 3px solid white;
}

.moments_avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 加载动画容器 */
.loading-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
}

.loading-container img {
  width: 60px;
  height: 60px;
  margin-bottom: 10px;
}
.moments_bg {
  cursor: pointer;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 220rpx;
}

.moments_bg::after {
  content: '点击更换背景图';
  position: absolute;
  top: 10rpx;
  right: 20rpx;
  font-size: 24rpx;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.3);
  padding: 4rpx 10rpx;
  border-radius: 8rpx;
  z-index: 10;
}


</style>
